import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';

import Loading from './Loading';
import { ERROR_STATUS_CODE_MAP, RESPONSE_CONFIG } from './config';
import { omit } from 'lodash-es'
import qs from 'qs'
import { download } from '@/utils';

let userStore: ReturnType<typeof useUserStore>;

/**
 * 请求拦截器
 * @param config 请求配置
 * @returns 格式化后的配置
 */
export function requestInterceptor(config: AxiosRequestConfig): AxiosRequestConfig {
  config.headers['Authori-zation'] = sessionStorage.getItem('token')
  if (config.headers && /^application\/x-www-form-urlencoded/.test(config.headers['content-type'] as string)) {
    config.data = qs.stringify(config.data)
  }

  Loading.open();
  return config;
}

/**
 * 请求拦截器错误处理
 * @param err 错误信息
 */
export function requestErrInterceptor(err: Error) {
  Loading.close();
  console.error(err);
}

const {
  code,
  msg,
  successCode,
} = RESPONSE_CONFIG;
/**
 * 请求响应拦截器
 * @param response 请求响应
 */
export function responseInterceptor(response: AxiosResponse) {
  const { data } = response;
  Loading.close();
  if (data instanceof Blob) {
    return download(response)
  }
  if (data[code] === successCode) {
    return data.data as unknown
  } else if (data[code] === undefined) {
    return { deptList: data }
  } else {
    const { text, handler } = ERROR_STATUS_CODE_MAP[data[code]] || {};
    text ? handler(text) :
      AntNotification.error({
        message: '请求错误',
        description: data[msg]
      });
    return Promise.reject(data);
  }
}

/**
 * 请求响应错误处理
 * @param err 错误信息
 */
export function responseErrInterceptor(err: AxiosError) {
  Loading.close();
  const { text, handler } =
    ERROR_STATUS_CODE_MAP[err.response?.status || 'default'] || ERROR_STATUS_CODE_MAP.default;
  handler(text);
  return Promise.reject(err);
}